package cnblogs.guzb.config;

import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 第一个数据源，同时也是主数据源配置, 查询的数据库为 biz1.sqlite3
 * 通过 MapperScan 注解来指定本 SqlSessionFactory 适用的 Mapper 类是哪些
 */
@MapperScan(
        basePackages = {"cnblogs.guzb.biz1"},
        sqlSessionFactoryRef = "PrimarySqlSessionFactory"
)
@Configuration
public class PrimarySqlSessionFactoryConfig {

    // 表示这个数据源是默认数据源，多数据源情况下，必须指定一个主数据源
    @Primary
    @Bean(name = "PrimaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource getPrimaryDateSource() {
        // 这个MyBatis内置的无池化的数据源，仅仅用于演示，实际工程请更换成具体的数据源对象
        return new UnpooledDataSource();
    }

    @Primary
    @Bean(name = "PrimarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(
            @Qualifier("PrimaryDataSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        // 主数据源的XML SQL配置资源
        Resource[] xmlMapperResources = new PathMatchingResourcePatternResolver().getResources("classpath:mappers/primary/*.xml");
        bean.setMapperLocations(xmlMapperResources);
        return bean.getObject();
    }


    @Primary
    @Bean("PrimarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(
            @Qualifier("PrimarySqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

}
